/**
 * @file AuthContext.tsx
 * @description 认证相关的上下文管理，处理登录注册相关的状态和通信
 */

'use client'

import { createContext, useContext, useState, ReactNode, useEffect } from 'react'
import { message } from 'antd'
import { authService } from '@/lib/services/auth'

interface AuthContextType {
  // 用户状态相关
  user: {
    id: string;
    username: string;
    phone: string;
    email?: string;
    avatar?: string;
    role: 'user' | 'admin';
    status: 'active' | 'inactive';
  } | null;
  isAuthenticated: boolean;
  isAdmin: boolean;
  login: (usernameOrPhone: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  checkAuth: () => Promise<boolean>;

  // 登录类型相关
  loginType: 'phone' | 'password' | 'wechat'
  setLoginType: (type: 'phone' | 'password' | 'wechat') => void

  // 用户名相关
  username: string
  setUsername: (username: string) => void
  usernameError: string
  validateUsername: (value: string) => boolean

  // 手机号相关
  phone: string
  setPhone: (phone: string) => void
  phoneError: string
  validatePhone: (value: string) => boolean
  
  // 验证码相关
  verificationCode: string
  setVerificationCode: (code: string) => void
  verificationCodeError: string
  validateVerificationCode: (value: string) => boolean
  countdown: number
  setCountdown: (seconds: number) => void
  handleSendCode: () => Promise<void>
  
  // 密码相关
  password: string
  setPassword: (password: string) => void
  passwordError: string
  validatePassword: (value: string) => boolean
  confirmPassword: string
  setConfirmPassword: (password: string) => void
  confirmPasswordError: string
  validateConfirmPassword: (value: string) => boolean
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: ReactNode }) {
  // 状态管理
  const [user, setUser] = useState<AuthContextType['user']>(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [username, setUsername] = useState('');
  const [usernameError, setUsernameError] = useState('')
  const [phone, setPhone] = useState('')
  const [phoneError, setPhoneError] = useState('')
  const [verificationCode, setVerificationCode] = useState('')
  const [verificationCodeError, setVerificationCodeError] = useState('')
  const [countdown, setCountdown] = useState(0)
  const [password, setPassword] = useState('')
  const [passwordError, setPasswordError] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [confirmPasswordError, setConfirmPasswordError] = useState('')
  const [loginType, setLoginType] = useState<'phone' | 'password' | 'wechat'>('phone')

  // 用户名验证
  const validateUsername = (value: string) => {
    if (!value) {
      setUsernameError('请输入用户名')
      return false
    }
    if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]{2,20}$/.test(value)) {
      setUsernameError('用户名只能包含字母、数字、下划线和中文，长度2-20位')
      return false
    }
    setUsernameError('')
    return true
  }

  // 手机号验证
  const validatePhone = (value: string) => {
    // 清除所有非数字字符
    const cleanValue = value.replace(/\D/g, '')
    
    if (!cleanValue) {
      setPhoneError('请输入手机号')
      return false
    }

    // 检查是否是11位数字
    if (cleanValue.length !== 11) {
      setPhoneError('手机号必须是11位数字')
      return false
    }

    // 检查是否以1开头
    if (!cleanValue.startsWith('1')) {
      setPhoneError('手机号必须以1开头')
      return false
    }

    // 检查第二位是否在3-9之间
    const secondDigit = parseInt(cleanValue[1])
    if (secondDigit < 3 || secondDigit > 9) {
      setPhoneError('手机号第二位必须在3-9之间')
      return false
    }

    // 如果所有验证都通过
    setPhoneError('')
    // 自动格式化手机号
    if (value !== cleanValue) {
      setPhone(cleanValue)
    }
    return true
  }

  // 验证码验证
  const validateVerificationCode = (value: string) => {
    if (!value) {
      setVerificationCodeError('请输入验证码')
      return false
    }
    if (!/^\d{6}$/.test(value)) {
      setVerificationCodeError('验证码必须是6位数字')
      return false
    }
    setVerificationCodeError('')
    return true
  }

  // 密码验证
  const validatePassword = (value: string) => {
    if (!value) {
      setPasswordError('请输入密码')
      return false
    }
    if (value.length < 6) {
      setPasswordError('密码长度不能小于6位')
      return false
    }
    if (!/^[a-zA-Z0-9_]{6,20}$/.test(value)) {
      setPasswordError('密码只能包含字母、数字和下划线，长度6-20位')
      return false
    }
    setPasswordError('')
    return true
  }

  // 确认密码验证
  const validateConfirmPassword = (value: string) => {
    if (!value) {
      setConfirmPasswordError('请确认密码')
      return false
    }
    if (value !== password) {
      setConfirmPasswordError('两次输入的密码不一致')
      return false
    }
    setConfirmPasswordError('')
    return true
  }

  // 发送验证码
  const handleSendCode = async () => {
    try {
      if (!validatePhone(phone)) return

      await authService.sendVerificationCode({
        phone,
        type: 'register'
      })
      
      message.success('验证码已发送')
      setCountdown(60)
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer)
            return 0
          }
          return prev - 1
        })
      }, 1000)
    } catch {
      // 错误已经在 handleError 中处理
    }
  }

  // 检查认证状态
  const checkAuth = async () => {
    console.log('开始检查认证状态...');
    try {
      // 首先检查是否有访问令牌
      const accessToken = authService.getAccessToken();
      
      if (!accessToken) {
        setUser(null);
        setIsAuthenticated(false);
        setIsAdmin(false);
        return false;
      }

      // 验证令牌
      const response = await authService.verifyToken();
      
      if (response.data?.valid) {
        try {
          const userResponse = await authService.getCurrentUser();
          
          if (userResponse.data) {
            const userData = userResponse.data;
            setUser({
              id: userData.id,
              username: userData.username,
              phone: userData.phone || '',
              email: userData.email,
              avatar: userData.avatar,
              role: userData.role || 'user',
              status: (userData.status as 'active' | 'inactive') || 'active'
            });
            setIsAuthenticated(true);
            // 根据角色判断是否为管理员
            const isAdminUser = userData.role === 'admin';
            setIsAdmin(isAdminUser);
            return isAdminUser;
          } else {
            setUser(null);
            setIsAuthenticated(false);
            setIsAdmin(false);
            return false;
          }
        } catch (userError) {
          setUser(null);
          setIsAuthenticated(false);
          setIsAdmin(false);
          return false;
        }
      } else {
        setUser(null);
        setIsAuthenticated(false);
        setIsAdmin(false);
        return false;
      }
    } catch (error) {
      setUser(null);
      setIsAuthenticated(false);
      setIsAdmin(false);
      return false;
    }
  };

  // 登录
  const login = async (usernameOrPhone: string, password: string) => {
    try {
      const response = await authService.login({ 
        username_or_phone: usernameOrPhone,
        password 
      });
      if (response.data) {
        const userData = response.data.user;
        setUser({
          id: userData.id,
          username: userData.username,
          phone: userData.phone || '',
          email: userData.email,
          avatar: userData.avatar,
          role: userData.role || 'user',
          status: (userData.status as 'active' | 'inactive') || 'active'
        });
        setIsAuthenticated(true);
        // 根据角色判断是否为管理员
        setIsAdmin(userData.role === 'admin');
      }
    } catch (error) {
      message.error('登录失败');
      throw error;
    }
  };

  // 登出
  const logout = async () => {
    try {
      await authService.logout();
      setUser(null);
      setIsAuthenticated(false);
      setIsAdmin(false);
    } catch (error) {
      message.error('登出失败');
      throw error;
    }
  };

  // 在组件挂载时检查认证状态
  useEffect(() => {
    checkAuth().catch(error => {
      console.error('Failed to check auth status:', error);
    });
  }, []);

  const value = {
    // 用户状态相关
    user,
    isAuthenticated,
    isAdmin,
    login,
    logout,
    checkAuth,

    // 登录类型相关
    loginType,
    setLoginType: (value: 'phone' | 'password' | 'wechat') => {
      setLoginType(value);
    },

    username,
    setUsername: (value: string) => {
      setUsername(value)
      validateUsername(value)
    },
    usernameError,
    validateUsername,

    phone,
    setPhone: (value: string) => {
      setPhone(value)
      validatePhone(value)
    },
    phoneError,
    validatePhone,

    verificationCode,
    setVerificationCode: (value: string) => {
      setVerificationCode(value)
      validateVerificationCode(value)
    },
    verificationCodeError,
    validateVerificationCode,
    countdown,
    setCountdown,
    handleSendCode,

    password,
    setPassword: (value: string) => {
      setPassword(value)
      validatePassword(value)
    },
    passwordError,
    validatePassword,

    confirmPassword,
    setConfirmPassword: (value: string) => {
      setConfirmPassword(value)
      validateConfirmPassword(value)
    },
    confirmPasswordError,
    validateConfirmPassword,
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
} 